
<!--公用组件：固定宽度的带图标的输入框
      /**
      * @author 龙伟
      * @date 2019年10月24日
      * @param isUpload: 上传or展示 pid、fileClass：上传文件所需参数 displayFile：展示文件的数据数组 handleFile: 传递变更的数据给父组件
      * 用法：
      展示
        <yt-template-upload :isupload="false"></yt-template-upload>
      上传
        <yt-template-upload @HandleFile="handleFile"></yt-template-upload>
      */
      * 用法：
      */
       -->
<template>
  <div class="templateUpload" style="display: flex">
    <el-input v-model="value2" style="display: none;"></el-input>
    <template v-if="isUpload">
      <el-upload
        :action="actionURL"
        :list-type="listType"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :on-exceed="handleExceed"
        :on-error="handleError"
        :on-success="handleSuccess"
        :data="updateParam"
        :before-upload="beforeUpload"
        :limit="limit"
        :file-list="fileList"
      >
        <i class="el-icon-upload2 yt-icon-upload2"></i>
      </el-upload>
      <div v-if="timeData" style="margin-left: 10px">
        <i class="el-icon-download yt-icon-download" @click="jointDownLoadURLLong()"></i>
        <span style="font-size: 13px;color: #606266">{{ uploadTime }}:{{ timeData }}</span>
      </div>
    </template>
    <template v-else>
      <div class="show-file">
        <div class="img-wrappar" v-for="file in displayFile" :key="file.id">
          <img :src="filterImg(file)" style="width: 100%; height: 100%;" />
          <i class="file-name">{{ file.name }}</i>
          <div class="bg-view" @click.stop="forbidClick">
            <span>
              <i class="el-icon-zoom-in" @click="handlePictureCardPreview(file)"/>
            </span>
            <span>
              <a :href="jointDownLoadURL(file)">
                <i class="el-icon-download" />
              </a>
            </span>
          </div>
        </div>
      </div>
    </template>
    <el-dialog :visible.sync="dialogVisible" append-to-body @close="close">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
  import doc from '@/assets/images/file_img/doc.png';
  import pdf from '@/assets/images/file_img/pdf.png';
  import ppt from '@/assets/images/file_img/ppt.png';
  import xls from '@/assets/images/file_img/xls.png';
  // import { queryDetail } from '@/api/scheduleManager/worksDetails';

  export default {
    name: 'templateUpload',
    props: {
      value: {
        type: String,
        default: ''
      },
      createTime: {
        type: String,
        default: ''
      },
      listData: {
        type: String,
        default: ''
      },
      isUpload: {
        // 是否是上传
        type: Boolean,
        default: true
      },
      pid: {
        type: String,
        default: ''
      },
      fileClass: {
        type: String,
        default: ''
      },
      limit: {
        type: Number,
        default: 10
      },
      displayFile: {
        type: Array,
        default() {
          return [];
        }
      },
      // 弹出层上传bug hack
      reSet: {
        type: Array,
        default() {
          return [];
        }
      }
    },
    data() {
      return {
        displayIdUid: '',
        timeData: '',
        uploadTime: this.$t('scheduleManager.worksDetails.uploadTime'),
        listType: 'fileList',
        userId: '',
        updateParam: {},
        dialogImageUrl: '',
        dialogVisible: false,
        fileList: [], // 上传成功的资源数组
        deleteIds: [], // 删除的资源ID数组
        fileIds: [], // 保留的资源ID数组
        isCancel: false // 是否是取消上传图片
      };
    },
    mounted() {
      this.timeData = this.createTime
      this.displayIdUid = this.value
      // if (this.$route.query.progressId) {
      //   queryDetail({ progressId: this.$route.query.progressId }).then(res => {
      //     if (this.listData === 'completionCertificateFile') {
      //       this.timeData = res.data.projectProgress.completionCertificateFile;
      //       this.displayIdUid = res.data.projectProgress.completionCertificateFileId;
      //     } else if (this.listData === 'satisfactionSurveyFile') {
      //       this.timeData = res.data.projectProgress.satisfactionSurveyFile;
      //       this.displayIdUid = res.data.projectProgress.satisfactionSurveyFileId;
      //     }
      //   });
      // }
      this.$emit('input', this.value);
      this.userId = this.$store.getters.info.id || '';
      if (this.$store.getters.sessionId) {
        this.updateParam.sessionId = this.$store.getters.sessionId;
        this.updateParam.fileClass = this.fileClass;
        this.updateParam.pid = this.pid;
      }
      if (this.displayFile.length > 0) {
        this.delDisplayFile();
      }
    },
    computed: {
      value2: {
        get() {
          return this.value;
        },
        set(val) {
          this.$emit('input', val);
          // this.$emit('searchChange', val)
        }
      },
      actionURL() {
        if (this.listData === 'completionCertificateFile') {
          return '/api/admin/excel/uploadProgress/' + this.userId + '/0';
        } else if (this.listData === 'satisfactionSurveyFile') {
          return '/api/admin/excel/uploadProgress/' + this.userId + '/1';
        } else if (this.listData === 'projectWorkUpload') {
          return '/api/admin/excel/uploadProgress/' + this.userId + '/2';
        }
      },
      downloadURL() {
        return '/pocomponent/file/downloadFile/w/v1?sessionId=&isAbbreviation=Y&id=';
      }
    },
    methods: {
      // eslint-disable-next-line no-unused-vars
      beforeRemove(file, fileList) {
        if (this.isCancel) {
          this.isCancel = false;
        } else {
          return new Promise((resolve, reject) => {
            this.$actionFail.show({
              title: '操作后无法取消!',
              content: '删除后无法取消，确认删除？',
              type: 1, // 1有确认按钮  0无确认按钮
              callback: () => resolve(),
              cancel: () => reject()
            });
          });
        }
      },
      // eslint-disable-next-line no-unused-vars
      handleRemove(file, fileList) {
        // 删除文件
        if (!file.id && !file.response) {
          return;
        }
        const id = file.id || file.response.id;
        this.deleteIds.push(id);
        // 从上传成功数组中，移除被删除的文件ID
        this.fileIds.splice(this.fileIds.findIndex(item => item === id), 1);
        this.fileList.splice(
          this.fileList.findIndex(item => (item.id || item.response.id) === id),
          1
        );
        const deleteStr =
          this.deleteIds.length !== 0 ? this.deleteIds.join(',') : '';
        const fileStr = this.fileIds.length !== 0 ? this.fileIds.join(',') : '';
        // 实时返回结果数组（存储了文件ID）
        this.$emit('HandleFile', { fileId: fileStr, deleteIds: deleteStr });
      },
      handlePictureCardPreview(file) {
        // 预览
        const extStart = file.name.lastIndexOf('.');
        const ext = file.name.substring(extStart, file.name.length).toUpperCase();
        if (
          ext !== '.PNG' &&
          ext !== '.GIF' &&
          ext !== '.JPG' &&
          ext !== '.JPEG'
        ) {
          // 判断文件是否是图片类型
          // 下载文档
          window.location.href = this.jointDownLoadURL(file);
        } else {
          this.dialogImageUrl = this.jointDownLoadURL(file);
          this.dialogVisible = true;
        }
      },
      handleExceed() {
        // 上传限制
        this.$message('最多上传10张');
      },
      // eslint-disable-next-line no-unused-vars
      handleError(file, fileList, err) {
        // 上传失败
        this.$message.error('上传失败');
      },
      // eslint-disable-next-line no-unused-vars
      handleSuccess(response, file, fileList) {
        // 上传成功
        if (this.checkRes(response)) {
          // const param = this.filterData(file);
          // 实时返回结果数组（存储了文件ID）
          // this.$emit('HandleFile', param, this.fileList);
          this.$emit('HandleFile', this.fileList);
        } else {
          // 上传失败重置数组
          this.fileList = [...this.fileList];
        }
      },
      beforeUpload(file) {
        // 上传前 钩子函数 。 上传附件大小不能超过10M
        const extStart = file.name.lastIndexOf('.');
        const ext = file.name.substring(extStart, file.name.length).toUpperCase();
        // if (
        //   ext !== '.PNG' &&
        //   ext !== '.GIF' &&
        //   ext !== '.JPG' &&
        //   ext !== '.JPEG' &&
        //   ext !== '.DOC' &&
        //   ext !== '.DOCX' &&
        //   ext !== '.XLS' &&
        //   ext !== '.XLSX' &&
        //   ext !== '.PPT' &&
        //   ext !== '.PPTX' &&
        //   ext !== '.PDF'
        // )
        if (
          ext !== '.PNG' &&
          ext !== '.GIF' &&
          ext !== '.JPG' &&
          ext !== '.JPEG' &&
          ext !== '.PDF'
        ) {
          // 判断文件是否是图片类型
          this.$message({
            message: '此类型文件不能上传',
            type: 'warning'
          });
          this.isCancel = true;
          return false;
        }
        const fileSize = file.size;
        if (!fileSize || fileSize === 0) {
          this.$message({
            message: '文件或已损坏，请正确选择文件',
            type: 'warning'
          });
          return false;
        }
        if (fileSize > 10000000) {
          this.$message({
            message: '上传文件大小不能超过10M',
            type: 'warning'
          });
          return false;
        }
      },
      checkRes(res) {
        // 验证返回值
        if (res.code === '20' || res.code === '21') {
          let message;
          if (res.code === '20') {
            message = '缺少sessionId，请重新登入';
          } else if (res.code === '21') {
            message = '无效的sessionId，请重新登入';
          }
          this.$message.error(message);
          return false;
        } else if (res.code !== '0') {
          this.timeData = res.data.createTime;
          this.displayIdUid = res.data.uid;

          // if (
          //   res.subErrors.length !== 0 &&
          //   res.subErrors[0].message &&
          //   res.subErrors[0].message.length !== 0
          // ) {
          //   // 判断错误信息
          //   message = res.subErrors[0].message;
          // } else {
          //   message = res.msg;
          // }
          // this.$message.error(message);
          // return false;
        }
        return true;
      },
      filterData(file) {
        // 过滤数据
        const extStart = file.name.lastIndexOf('.');
        const ext = file.name.substring(extStart, file.name.length).toUpperCase();
        if (
          ext !== '.PNG' &&
          ext !== '.GIF' &&
          ext !== '.JPG' &&
          ext !== '.JPEG'
        ) {
          // 判断上传的文件是否是图片类型
          let urlImg;
          if (ext === '.DOC' || ext === '.DOCX') {
            urlImg = doc;
          } else if (ext === '.XLS' || ext === '.XLSX') {
            urlImg = xls;
          } else if (ext === '.PPT' || ext === '.PPTX') {
            urlImg = ppt;
          } else if (ext === '.PDF') {
            urlImg = pdf;
          } else {
            urlImg = '';
          }
          this.fileList.push({
            name: file.name,
            url: urlImg,
            response: { ...file.response }
          });
        } else {
          this.fileList.push(file);
        }
        console.log(file.response);
        if (file.data) {
          this.fileIds.push(file.response.id);
        } else {
          this.$message.error('后台返回文件id为nil');
        }
        // 拼接回传数据
        const deleteStr =
          this.deleteIds.length !== 0 ? this.deleteIds.join(',') : '';
        const fileStr = this.fileIds.length !== 0 ? this.fileIds.join(',') : '';
        return { fileId: fileStr, deleteIds: deleteStr };
      },
      filterImg(item) {
        // 判断文件类型，返回相应显示的图片
        const extStart = item.name.lastIndexOf('.');
        const ext = item.name.substring(extStart, item.name.length).toUpperCase();

        if (
          ext !== '.PNG' &&
          ext !== '.GIF' &&
          ext !== '.JPG' &&
          ext !== '.JPEG'
        ) {
          // 判断上传的文件是否是图片类型
          if (ext === '.DOC' || ext === '.DOCX') {
            return doc;
          } else if (ext === '.XLS' || ext === '.XLSX') {
            return xls;
          } else if (ext === '.PPT' || ext === '.PPTX') {
            return ppt;
          } else if (ext === '.PDF') {
            return pdf;
          } else {
            return '';
          }
        } else {
          return item.url;
        }
      },
      jointDownLoadURLLong() {
        const a = document.createElement('a');
        const href = '/api/admin/excel/downloadProgressFileById?id=' + this.displayIdUid;
        a.download = Date.now();
        a.href = href;
        a.click();
      },
      jointDownLoadURL(file) {
        // 预览和下载，拼接URL
        const url = file.url;
        const base_url = this.$UPLOAD_BASE_API;
        if (url.indexOf(base_url) >= 0 && file.id) {
          // 若url包含base_url且有file中存在文件id，则说明该文件是网络获取的，否则为本地获取上传的
          return url + '&isAbbreviation=Y';
        }

        // 判断是不是文档类型
        const extStart = file.name.lastIndexOf('.');
        const ext = file.name.substring(extStart, file.name.length).toUpperCase();
        if (
          ext.indexOf('DOC') >= 0 ||
          ext.indexOf('PPT') >= 0 ||
          ext.indexOf('XLS') >= 0 ||
          ext.indexOf('PDF') >= 0
        ) {
          if (file.response) {
            return this.downloadURL + file.response.id;
          } else {
            if (file.id) {
              return this.downloadURL + file.id;
            }
          }
        }
        return url;
      },
      close() {
        // this.dialogImageUrl = ''
      },
      // 处理displayFile
      delDisplayFile() {
        const list = [...this.displayFile];
        if (this.isUpload) {
          list.map(item => {
            item.url = this.filterImg(item); // 更换对应类型的显示图片
            return item;
          });
        }
        this.fileList = list;
        this.fileIds = [];
        this.displayFile.forEach(item => {
          this.fileIds.push(item.id);
        });
      }
    },
    watch: {
      displayIdUid(val) {
        this.$emit('input', val);
      },
      pid() {
        if (this.pid && this.pid.length !== 0) {
          this.updateParam.pid = this.pid;
        }
      },
      displayFile(val, old) {
        if (!old.length && this.displayFile.length) {
          this.delDisplayFile();
        }
      },
      reSet() {
        const list = [...this.reSet];
        if (this.isUpload) {
          list.map(item => {
            item.url = this.filterImg(item); // 更换对应类型的显示图片
            return item;
          });
        }
        this.fileList = list;
        this.reSet.forEach(item => {
          this.fileIds.push(item.id);
        });
      }
    }
  };
</script>

<style scoped lang="scss">
  .yt-icon-upload2,
  .yt-icon-download {
    cursor: pointer;
    color: #2ebd8f;
    font-size: 20px;
  }
  .show-file {
    margin: 0;
    display: inline;
    vertical-align: top;
    .img-wrappar {
      overflow: hidden;
      background-color: #fff;
      border: 1px solid #c0ccda;
      box-sizing: border-box;
      width: 100px;
      height: 100px;
      margin: 0 8px 8px 0;
      display: inline-block;
      position: relative;
      .file-name {
        display: block !important;
        position: absolute;
        bottom: 0;
        right: 0;
        background-color: rgba(0, 0, 0, 0.5);
        width: 100%;
        margin: 0;
        color: white;
        text-align: center;
        font-size: 14px;
        height: 20px;
        line-height: 20px;
      }
      &:hover {
        .bg-view {
          position: absolute;
          top: 0;
          right: 0;
          height: 100%;
          width: 100%;
          background-color: rgba(0, 0, 0, 0.5);
          display: flex;
          justify-content: center;
          align-items: center;
          span {
            padding: 8px;
            color: white;
          }
        }
      }
    }
  }
  .file-preview {
    position: absolute;
    top: 0;
    right: 0;
    height: 100%;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .templateUpload{
    line-height: 36px;
  }
</style>
